package com.base.controller.login;

import com.base.config.Constant;
import com.base.model.LoginModel;
import com.base.model.authority.T_User;
import com.base.model.authority.T_UserRoles;
import com.base.model.log.T_Loginlog;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.pinion.util.StringUtil;
import com.zh_new.annotation.RouteBind;
import com.zh_new.util.IpAddr;
import com.zh_new.util.Pwd;
import org.apache.regexp.RE;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@ClearInterceptor(ClearLayer.ALL)
@RouteBind(path = "/Login", viewPath = "Index/Login")
public class LoginController extends Controller {

    public static Map<String, HttpSession> userMap = new HashMap<String, HttpSession>();

    public void index() {
        render("login.jsp");
    }

    /**
     * 登录
     */
    public void login() {
        String dlid = "";
        String pwd = "";
        if (null == getPara("dlid") || null == getPara("pwd") || getPara("dlid").trim().equals("") || getPara("pwd").trim().equals("")) {
            setAttr("dlid", getPara("dlid"));
            setAttr("pwd", getPara("pwd"));
            setAttr("mes", "alert('用户名或者密码未输入！')");
            render("login.jsp");
            return;
        }
        dlid = getPara("dlid");
        pwd = getPara("pwd");
        RE re = new RE("^[A-Za-z0-9]+$");
        if (!re.match(dlid) || !re.match(pwd)) {
            setAttr("dlid", dlid);
            setAttr("pwd", pwd);
            setAttr("mes", "alert('输入错误,用户名和密码为英文字母和数字组合！')");
            render("login.jsp");
            return;
        }
        T_User user = T_User.dao.exists(dlid);
        if (null != user) {
            if (user.get("pwd").equals(Pwd.encrypt(user.get("id") + pwd))) {
                if (user.getStr("usable").equals("1")) {
                    if (userMap.containsKey(dlid)) {
                        userMap.get(dlid).invalidate();
                        userMap.remove(dlid);
                    } else {
                        if (userMap.containsValue(getSession())) {
                            getSession().invalidate();
                        }
                    }
                    if (null != T_Loginlog.dao.findById(getSession().getId())) {
                        getSession().invalidate();
                    }
                    userMap.put(dlid, getSession(true));
                    T_Loginlog dljl = new T_Loginlog();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    dljl.set("sessionId", getSession().getId()).set("dlms", "正常").set("dltime", format.format(new Date())).set("u_id", user.get("id")).set("ip", IpAddr.getIpAddr(getRequest())).save();
                    LoginModel loginModel = new LoginModel();
                    loginModel.setUserId(user.getInt("id"));
                    loginModel.setDlId(user.getStr("dlid"));
                    loginModel.setUserName(user.getStr("name"));
                    loginModel.setUserStaffId(user.getStr("staff_id"));
                    /*******************************2015-2-3 10:05:00 Andersen 新增职位ID开始**********************/
                    loginModel.setPositionId(user.getInt("pid"));
                    /*******************************2015-2-3 10:05:00 Andersen 新增职位ID结束**********************/
                    loginModel.setSessionId(getSession().getId());
                    if (null != user.get("d_id")) {
                        loginModel.setDepartmentId(user.getInt("d_id"));
                        loginModel.setDepsname(user.getDept().getStr("sname"));
                    }
                    loginModel.setLo(user.getStr("lo"));
                    List<T_UserRoles> roles = user.getRoles();
                    if (null == roles || 0 == roles.size()) {
                        loginModel.setLimit("");
                    } else {
//                        loginModel.setRoleId(roles)
                        List<String> roleIds = new ArrayList<String>();
                        List<String> rlimits = new ArrayList<String>();
                        List<String> dblimits = new ArrayList<String>();
                        for (T_UserRoles userRoles : roles) {
                            //获取对应的role_id
                            roleIds.add("_" + userRoles.getInt("r_id").toString());
                            if (null != userRoles.getRole().getStr("xtlimit")) {
                                rlimits.add(userRoles.getRole().getStr("xtlimit").trim());
                            }
                            if (null != userRoles.getRole().getStr("dblimit")) {
                                dblimits.add(userRoles.getRole().getStr("dblimit").trim());
                            }
                        }
                        if (0 == rlimits.size()) {
                            loginModel.setLimit("");
                        } else {
                            loginModel.setLimit(StringUtil.distinctStr(rlimits));
                        }
                        if (0 == dblimits.size()) {
                            loginModel.setDblimit("");
                        } else {
                            loginModel.setDblimit(StringUtil.distinctStr(dblimits));
                        }
                        if (0 == roleIds.size()) {
                            loginModel.setRoleIds("");
                        } else {
                            loginModel.setRoleIds(StringUtil.distinctStr(roleIds));
                        }
                    }
                    setSessionAttr("loginModel", loginModel);
                    if (Constant.SERVER_NAME.equals("") || !Constant.SERVER_NAME.equals(getRequest().getServerName())) {
                        Constant.SERVER_NAME = getRequest().getServerName();
                        Constant.SERVER_PORT = getRequest().getServerPort() + "";
                        Constant.PATH_SHOW = "http://" + Constant.SERVER_NAME + ":" + Constant.SERVER_PORT + "/" + Constant.PROJECT_NAME + Constant.PATH_REPORT;
                    }
                    setCookie("oa_sessionId", loginModel.getSessionId(), 60 * 60 * 24);
                    redirect(getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + getRequest().getContextPath() + "/Main");
                } else {
                    setAttr("dlid", dlid);
                    setAttr("pwd", pwd);
                    setAttr("mes", "alert('用户已禁用！')");
                    render("login.jsp");
                }
            } else {
                setAttr("dlid", dlid);
                setAttr("pwd", pwd);
                setAttr("mes", "alert('用户名或者密码错误！')");
                render("login.jsp");
            }
        } else {
            setAttr("dlid", dlid);
            setAttr("pwd", pwd);
            setAttr("mes", "alert('用户名或者密码错误！')");
            render("login.jsp");
        }
    }

    /**
     * 注销
     */
    public void logout() throws Exception {
        if (getSession().getAttribute("loginModel") != null) {
            LoginModel loginModel = (LoginModel) getSession().getAttribute("loginModel");
            T_Loginlog dljl = T_Loginlog.dao.findById(loginModel.getSessionId());
            String dlId = loginModel.getDlId();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dljl.set("loDate", format.format(new Date())).set("dlms", "注销").update();
            try {
                userMap.get(dlId).invalidate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            userMap.remove(dlId);
        }
        if (getCookie("oa_sessionId") != null) {
            removeCookie("oa_sessionId");
        }
        redirect(getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + "/" + Constant.PROJECT_NAME);
    }

}
